import Taro from '@tarojs/taro';
import React, { useState, useEffect } from 'react';
import { View, Text, Image, Switch, ScrollView } from '@tarojs/components';
import { MaterialIcons } from 'taro-icons';
import './index.scss';

// 教练信息类型定义
interface CoachProfile {
  id: number;
  name: string;
  avatar: string;
  video: string; // 宣传视频
  phone: string;
  email: string;
  licenseType: string; // 准驾车型
  experience: number; // 驾龄（年）
  teachingYears: number; // 教学年限
  rating: number; // 评分
  introduction: string; // 个人介绍
  isOnline: boolean; // 是否在线
  autoAcceptAppointment: boolean; // 是否自动接受预约
  notificationEnabled: boolean; // 通知开关
  workingHours: {
    start: string; // 开始时间
    end: string; // 结束时间
  };
  native: string; // 籍贯信息
  supportEnglishTeaching: boolean; // 是否支持英文教学
  password: string; // 密码
  oldPassword: string; // 旧密码
  newPassword: string; // 新密码
  confirmPassword: string; // 确认新密码
}

const CoachSettingPage: React.FC = () => {
  const [profile, setProfile] = useState<CoachProfile | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isEditMode, setIsEditMode] = useState(false);
  const [tempProfile, setTempProfile] = useState<CoachProfile | null>(null);

  useEffect(() => {
    // 设置页面标题
    Taro.setNavigationBarTitle({ title: '教练设置' });
    // 加载教练信息
    loadCoachProfile();
  }, []);

  const loadCoachProfile = async () => {
    try {
      setIsLoading(true);
      // 模拟API调用
      // const response = await getCoachProfileApi();
      
      // 模拟数据
      const mockProfile: CoachProfile = {
        id: 1,
        name: '张教练',
        avatar: 'https://via.placeholder.com/100x100',
        video: 'https://via.placeholder.com/300x200?text=宣传视频',
        phone: '138****5678',
        email: 'coach@example.com',
        licenseType: 'C1, C2',
        experience: 8, // 8年驾龄
        teachingYears: 5, // 5年教学经验
        rating: 4.9,
        introduction: '从事驾驶教学5年，教学认真负责，注重安全，善于因材施教，通过率高。',
        isOnline: true,
        autoAcceptAppointment: false,
        notificationEnabled: true,
        workingHours: {
          start: '08:00',
          end: '20:00'
        },
        native: '北京', // 籍贯信息
        supportEnglishTeaching: true // 是否支持英文教学
      };
      
      setProfile(mockProfile);
      setTempProfile({ ...mockProfile });
    } catch (error) {
      console.error('加载教练信息失败:', error);
      Taro.showToast({
        title: '数据加载失败，请重试',
        icon: 'none'
      });
    } finally {
      setIsLoading(false);
    }
  };

  const handleEdit = () => {
    setIsEditMode(true);
  };

  const handleSave = async () => {
    if (!tempProfile) return;
    
    try {
      Taro.showLoading({ title: '保存中...' });
      
      // 模拟API调用
      // await updateCoachProfileApi(tempProfile);
      
      setProfile(tempProfile);
      setIsEditMode(false);
      
      Taro.hideLoading();
      Taro.showToast({
        title: '保存成功',
        icon: 'success'
      });
    } catch (error) {
      console.error('保存教练信息失败:', error);
      Taro.hideLoading();
      Taro.showToast({
        title: '保存失败，请重试',
        icon: 'none'
      });
    }
  };

  const handleCancel = () => {
    if (profile) {
      setTempProfile({ ...profile });
      setIsEditMode(false);
    }
  };

  const handleSwitchChange = (field: keyof CoachProfile, value: boolean) => {
    if (tempProfile) {
      setTempProfile({
        ...tempProfile,
        [field]: value
      });
    }
  };

  // 处理工作时间设置
  const handleUpdateWorkingHours = () => {
    // 实现工作时间选择
    Taro.showActionSheet({
      itemList: ['上午', '下午', '自定义'],
      success: (res) => {
        switch (res.tapIndex) {
          case 0: // 上午
            setTempProfile(prev => prev ? {...prev, workingHours: { start: '08:00', end: '12:00' }} : prev);
            Taro.showToast({
              title: '工作时间已设置为上午 08:00 - 12:00',
              icon: 'success'
            });
            break;
          case 1: // 下午
            setTempProfile(prev => prev ? {...prev, workingHours: { start: '14:00', end: '18:00' }} : prev);
            Taro.showToast({
              title: '工作时间已设置为下午 14:00 - 18:00',
              icon: 'success'
            });
            break;
          case 2: // 自定义
            // 这里可以实现更复杂的时间选择
            Taro.showToast({
              title: '自定义时间功能待实现',
              icon: 'none'
            });
            break;
          default:
            break;
        }
      }
    });
  };

  // 处理头像上传
  const handleAvatarUpload = () => {
    // 实现头像上传功能
    Taro.showActionSheet({
      itemList: ['从相册选择', '拍照'],
      success: (res) => {
        const sourceType = res.tapIndex === 0 ? 'album' : 'camera';
        // 调用相机或相册
        Taro.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: [sourceType],
          success: (chooseRes) => {
            // 这里可以上传图片到服务器
            Taro.showToast({
              title: '头像上传功能待实现',
              icon: 'none'
            });
          }
        });
      }
    });
  };

  // 处理宣传视频上传
  const handleVideoUpload = () => {
    // 实现视频上传功能
    Taro.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: 'back',
      success: (res) => {
        // 这里可以上传视频到服务器
        Taro.showToast({
          title: '视频上传功能待实现',
          icon: 'none'
        });
      }
    });
  };

  const handleChangePassword = () => {
    // 跳转到修改密码页面
    Taro.navigateTo({
      url: '/pages/change-password/index'
    });
  };

  // 处理籍贯修改
  const handleEditNative = () => {
    // 实现籍贯选择
    Taro.showModal({
      title: '修改籍贯',
      content: '请输入新的籍贯',
      editable: true,
      placeholderText: '例如：北京',
      success: (res) => {
        if (res.confirm) {
          const newNative = res.content?.trim();
          if (newNative) {
            setTempProfile(prev => prev ? {...prev, native: newNative} : prev);
            Taro.showToast({
              title: '籍贯已更新',
              icon: 'success'
            });
          }
        }
      }
    });
  };

  const handleLogout = () => {
    Taro.showModal({
      title: '退出登录',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          // 清除本地存储的登录信息
          Taro.removeStorageSync('token');
          Taro.removeStorageSync('userInfo');
          // 跳转到登录页面
          Taro.reLaunch({
            url: '/pages/login/index'
          });
        }
      }
    });
  };

  if (isLoading || !profile || !tempProfile) {
    return (
      <View className="loading-container">
        <Text>加载中...</Text>
      </View>
    );
  }

  return (
    <ScrollView className="coach-setting-page">
      {/* 个人信息卡片 */}
      <View className="profile-card">
        <View className="profile-header">
          <Image 
            className="coach-avatar" 
            src={tempProfile.avatar} 
            mode="aspectFill"
          />
          <View className="profile-info">
            <View className="name-rating">
              <Text className="coach-name">{tempProfile.name}</Text>
              <View className="rating-container">
                <MaterialIcons name="star" size={16} color="#faad14" />
                <Text className="rating-text">{tempProfile.rating}</Text>
              </View>
            </View>
            <Text className="coach-details">
              准驾车型：{tempProfile.licenseType} | {tempProfile.experience}年驾龄 | {tempProfile.teachingYears}年教学经验
            </Text>
          </View>
        </View>
        <Text className="coach-intro">{tempProfile.introduction}</Text>
      </View>
      
      {/* 个人信息编辑 */}
      <View className="setting-section">
        <Text className="section-title">个人信息</Text>
        <View className="setting-card">
          <View className="setting-item" onClick={handleAvatarUpload}>
            <View className="setting-label">
              <MaterialIcons name="camera-alt" size={20} color="#1890ff" />
              <Text className="setting-text">修改头像</Text>
            </View>
            <MaterialIcons name="chevron-right" size={24} color="#ccc" />
          </View>
          <View className="setting-item" onClick={handleVideoUpload}>
            <View className="setting-label">
              <MaterialIcons name="video-library" size={20} color="#52c41a" />
              <Text className="setting-text">宣传视频</Text>
            </View>
            <MaterialIcons name="chevron-right" size={24} color="#ccc" />
          </View>
              <View className="setting-item" onClick={() => handleEditNative()}>
        <View className="setting-label">
          <MaterialIcons name="location-on" size={20} color="#faad14" />
          <Text className="setting-text">籍贯</Text>
        </View>
        <View className="setting-value">
          <Text className="value-text">{tempProfile.native}</Text>
          <MaterialIcons name="chevron-right" size={24} color="#ccc" />
        </View>
      </View>
          <View className="setting-item">
            <View className="setting-label">
              <MaterialIcons name="translate" size={20} color="#fa8c16" />
              <Text className="setting-text">英文教学</Text>
            </View>
            <Switch 
              checked={tempProfile.supportEnglishTeaching}
              onChange={(e) => handleSwitchChange('supportEnglishTeaching', e.detail.value)}
              color="#fa8c16"
            />
          </View>
        </View>
      </View>

      {/* 工作设置 */}
      <View className="setting-section">
        <Text className="section-title">工作设置</Text>
        <View className="setting-card">
          <View className="setting-item">
            <View className="setting-label">
              <MaterialIcons name="radio-button-checked" size={20} color="#1890ff" />
              <Text className="setting-text">在线状态</Text>
            </View>
            <Switch 
              checked={tempProfile.isOnline}
              onChange={(e) => handleSwitchChange('isOnline', e.detail.value)}
              color="#1890ff"
            />
          </View>
          <View className="setting-item">
            <View className="setting-label">
              <MaterialIcons name="event-available" size={20} color="#52c41a" />
              <Text className="setting-text">自动接受预约</Text>
            </View>
            <Switch 
              checked={tempProfile.autoAcceptAppointment}
              onChange={(e) => handleSwitchChange('autoAcceptAppointment', e.detail.value)}
              color="#52c41a"
            />
          </View>
          <View className="setting-item" onClick={handleUpdateWorkingHours}>
            <View className="setting-label">
              <MaterialIcons name="access-time" size={20} color="#faad14" />
              <Text className="setting-text">工作时间设置</Text>
            </View>
            <View className="setting-value">
              <Text className="value-text">
                {tempProfile.workingHours.start} - {tempProfile.workingHours.end}
              </Text>
              <MaterialIcons name="chevron-right" size={24} color="#ccc" />
            </View>
          </View>
        </View>
      </View>

      {/* 通知设置 */}
      <View className="setting-section">
        <Text className="section-title">通知设置</Text>
        <View className="setting-card">
          <View className="setting-item">
            <View className="setting-label">
              <MaterialIcons name="notifications-active" size={20} color="#fa8c16" />
              <Text className="setting-text">消息通知</Text>
            </View>
            <Switch 
              checked={tempProfile.notificationEnabled}
              onChange={(e) => handleSwitchChange('notificationEnabled', e.detail.value)}
              color="#fa8c16"
            />
          </View>
        </View>
      </View>

      {/* 账户设置 */}
      <View className="setting-section">
        <Text className="section-title">账户设置</Text>
        <View className="setting-card">
          <View className="setting-item" onClick={handleChangePassword}>
            <View className="setting-label">
              <MaterialIcons name="lock" size={20} color="#722ed1" />
              <Text className="setting-text">修改密码</Text>
            </View>
            <MaterialIcons name="chevron-right" size={24} color="#ccc" />
          </View>
          <View className="setting-item">
            <View className="setting-label">
              <MaterialIcons name="phone" size={20} color="#13c2c2" />
              <Text className="setting-text">手机号</Text>
            </View>
            <Text className="value-text">{tempProfile.phone}</Text>
          </View>
          <View className="setting-item">
            <View className="setting-label">
              <MaterialIcons name="email" size={20} color="#eb2f96" />
              <Text className="setting-text">邮箱</Text>
            </View>
            <Text className="value-text">{tempProfile.email}</Text>
          </View>
        </View>
      </View>

      {/* 退出登录按钮 */}
      <View className="logout-btn" onClick={handleLogout}>
        <Text className="logout-text">退出登录</Text>
      </View>

      {/* 编辑/保存按钮 */}
      <View className="action-buttons">
        {isEditMode ? (
          <>
            <View className="cancel-btn" onClick={handleCancel}>
            <Text className="cancel-btn-text">取消</Text>
          </View>
          <View className="save-btn" onClick={handleSave}>
            <Text className="save-btn-text">保存修改</Text>
          </View>
          </>
        ) : (
          <View className="edit-btn" onClick={handleEdit}>
            <MaterialIcons name="edit" size={20} color="#fff" />
            <Text className="edit-btn-text">编辑资料</Text>
          </View>
        )}
      </View>
    </ScrollView>
  );
};

export default CoachSettingPage;